﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;

namespace SisocanaFronEnd.Services
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "FileTransferService" in code, svc and config file together.
    public class FileTransferService : IFileTransferService
    {
        public ResponseMessage SaveFile(UploadStreamMessage uploadMessage)
        {
            string fileName = uploadMessage.fileName;
            Stream dataStream = uploadMessage.dataStream;
            try
            {
                string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
                string directoryName = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(directoryName))
                    Directory.CreateDirectory(directoryName);

                using (FileStream fileStream = File.Create(fullPath))
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead = dataStream.Read(buffer, 0, buffer.Length);
                    while (bytesRead > 0)
                    {
                        fileStream.Write(buffer, 0, bytesRead);
                        bytesRead = dataStream.Read(buffer, 0, buffer.Length);
                    }
                }

                // Si es un archivo comprimido lo descomprime en el directorio.
                if (Path.GetExtension(fileName).Equals(".zip"))
                {
                    using (FileStream file = new FileStream(fullPath, FileMode.Open))
                    {
                        ZipFile zipFile = new ZipFile(file);
                        foreach (ZipEntry zipEntry in zipFile)
                        {
                            if (!zipEntry.IsFile) continue;

                            String entryFileName = Path.GetFileName(zipEntry.Name);
                            byte[] buffer = new byte[4096];
                            Stream zipStream = zipFile.GetInputStream(zipEntry);
                            String fullZipToPath = Path.Combine(directoryName, entryFileName);
                            using (FileStream streamWriter = File.Create(fullZipToPath))
                            {
                                StreamUtils.Copy(zipStream, streamWriter, buffer);
                            }
                        }
                        zipFile.Close();
                    }
                }
                return new ResponseMessage(true);
            }
            catch (Exception)
            {
                return new ResponseMessage(false);
            }
            finally
            {
                dataStream.Close();
            }
        }
    }
}
